package zuk.clipvietfun.getdata;

import static zuk.clipvietfun.plus.Const.FILE_NAME_LOCATION;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Scanner;

import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;

import android.util.Log;
public class GetDataFromUrl {

	String fileTxt;
	File dir;
	File file;
	public GetDataFromUrl(String fileTxt, File dir) {
		this.dir = dir;
		this.fileTxt = fileTxt;
	}

	public String getData() {
		String data = null;
		try {
			if (!dir.exists()) {
				dir.mkdirs();
			}
			String fileName[] = fileTxt.split("/");
			file = new File(dir, fileName[FILE_NAME_LOCATION]);
			if(!file.exists()){
				file.createNewFile();
				HttpGet get = new HttpGet(fileTxt);
				HttpResponse response = new DefaultHttpClient().execute(get);
				data = EntityUtils.toString(response.getEntity(),HTTP.UTF_8);
				OutputStream fOut = new FileOutputStream(file);
				byte[] bData = data.toString().getBytes();
				fOut.write(bData);
				fOut.flush();
				fOut.close();
				Log.e("Download data!!!!", "file " + fileName[FILE_NAME_LOCATION] + ".txt downloaded\n" + "file length" + Long.toString(file.length()));
				return data;
			}else {
				Log.e("Files length", Long.toString(file.length()));
				Log.e("Load data!!!!", "file " + fileName[FILE_NAME_LOCATION] + " Loaded");
				FileInputStream fis = new FileInputStream(file);
				data = new Scanner(fis,"UTF-8").useDelimiter("\\A").next();
				return data;
			}

		} catch (ClientProtocolException e) {
			e.printStackTrace();
			return null;
		} catch (IOException e) {
			Log.e("GetDataFromUrl!!", "IOException e");
			file.delete();
			getData();
			e.printStackTrace();
			return null;
		}
	}




}
